package com.bdqn.tour.dao;

import com.bdqn.tour.pojo.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class TicketDao {
    private static final Logger logger = LoggerFactory.getLogger(TicketDao.class);
    private Connection connection;

    public TicketDao(Connection connection) {
        this.connection = connection;
    }
     // 执行SQL查询并返回所有机票信息的列表
    // 参数: sql - 要执行的SQL查询语句
    // 返回值: 包含所有机票信息的列表
    public List<Ticket> getAllTickets() throws SQLException {
        List<Ticket> tickets = new ArrayList<>();
        String sql = "SELECT * FROM tickets";
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
            while (resultSet.next()) {
                tickets.add(mapToTicket(resultSet));
            }
        }
        return tickets;
    }
    // 向数据库中添加一个新的机票信息
   // 参数: ticket - 要添加的机票对象
   // 抛出: SQLException - 如果数据库操作失败
    public void addTicket(Ticket ticket) throws SQLException {
        //记录添加机票的信息日志
        logger.info("Adding ticket: id={}, type={}, ticketType={}, departureCity={}, arrivalCity={}, departureDate={}, startTime={}, endTime={}, price={}, hasInfantOption={}, hasChildOption={}",
                ticket.getId(), ticket.getType(), ticket.getTicketType(), ticket.getDepartureCity(), ticket.getArrivalCity(), ticket.getDepartureDate(), ticket.getStartTime(), ticket.getEndTime(), ticket.getPrice(), ticket.isHasInfantOption(), ticket.isHasChildOption());
        //验证机票对象是否为空
        if (ticket == null) {
            throw new IllegalArgumentException("Ticket object cannot be null");
        }
        //验证机票ID是否为空
        if (ticket.getId() == null) {
            throw new IllegalArgumentException("Ticket ID cannot be null");
        }
        //验证机票类型是否为空
        if (ticket.getType() == null) {
            throw new IllegalArgumentException("Ticket type cannot be null");
        }
        //验证机票类型是否为空
        if (ticket.getTicketType() == null) {
            throw new IllegalArgumentException("Ticket type cannot be null");
        }
        //验证出发城市是否为空
        if (ticket.getDepartureCity() == null) {
            throw new IllegalArgumentException("Departure city cannot be null");
        }
        //验证到达城市是否为空
        if (ticket.getArrivalCity() == null) {
            throw new IllegalArgumentException("Arrival city cannot be null");
        }
        //验证出发日期是否为空
        if (ticket.getDepartureDate() == null) {
            throw new IllegalArgumentException("Departure date cannot be null");
        }
        //验证出发时间是否为空
        if (ticket.getStartTime() == null) {
            throw new IllegalArgumentException("Start time cannot be null");
        }
        //验证到达时间是否为空
        if (ticket.getEndTime() == null) {
            throw new IllegalArgumentException("End time cannot be null");
        }
        //准备SQL语句
        String sql = "INSERT INTO tickets (id,type, ticketType, departure_city, arrival_city, departure_date, start_time, end_time, price, has_infant_option, has_child_option) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            //设置参数
            preparedStatement.setString(1, ticket.getId());
            preparedStatement.setString(2, ticket.getType());
            preparedStatement.setString(3, ticket.getTicketType());
            preparedStatement.setString(4, ticket.getDepartureCity());
            preparedStatement.setString(5, ticket.getArrivalCity());
            preparedStatement.setDate(6, Date.valueOf(ticket.getDepartureDate()));
            preparedStatement.setTime(7, Time.valueOf(ticket.getStartTime()));
            preparedStatement.setTime(8, Time.valueOf(ticket.getEndTime()));
            preparedStatement.setDouble(9, ticket.getPrice());
            preparedStatement.setBoolean(10, ticket.isHasInfantOption());
            preparedStatement.setBoolean(11, ticket.isHasChildOption());
            //执行更新操作
            preparedStatement.executeUpdate();
        }
    }

    // 从数据库中删除指定ID的机票信息
   // 参数: id - 要删除的机票的ID
   // 抛出: SQLException - 如果数据库操作失败
    public void deleteTicket(String id) throws SQLException {
        //准备SQL删除语句
        String sql = "DELETE FROM tickets WHERE id = ?";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            //设置参数
            preparedStatement.setString(1, id);
            //执行删除操作
            preparedStatement.executeUpdate();
        }
    }
    // 根据ID从数据库中获取机票信息
   // 参数: id - 要查询的机票的ID
   // 返回值: 匹配ID的机票对象，如果未找到则返回null
   // 抛出: SQLException - 如果数据库操作失败
    public Ticket getTicketById(String id) throws SQLException {
        //准备SQL查询语句
        String sql = "SELECT * FROM tickets WHERE id = ?";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            //设置参数
            preparedStatement.setString(1, id);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                //如果结果集有下一行，则返回匹配的机票对象
                if (resultSet.next()) {
                    return mapToTicket(resultSet);
                }
            }
        }
        return null;
    }
    // 更新数据库中的机票信息
    // 参数: ticket - 要更新的机票对象
   // 抛出: SQLException - 如果数据库操作失败
    public void updateTicket(Ticket ticket) throws SQLException {
        //准备SQL更新语句
        String sql = "UPDATE tickets SET ticketType = ?, departure_city = ?, arrival_city = ?, departure_date = ?, start_time = ?, end_time = ?, price = ?, has_infant_option = ?, has_child_option = ? WHERE id = ?";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            //设置参数
            preparedStatement.setString(1, ticket.getTicketType());
            preparedStatement.setString(2, ticket.getDepartureCity());
            preparedStatement.setString(3, ticket.getArrivalCity());
            preparedStatement.setDate(4, Date.valueOf(ticket.getDepartureDate()));
            preparedStatement.setTime(5, Time.valueOf(ticket.getStartTime()));
            preparedStatement.setTime(6, Time.valueOf(ticket.getEndTime()));
            preparedStatement.setDouble(7, ticket.getPrice());
            preparedStatement.setBoolean(8, ticket.isHasInfantOption());
            preparedStatement.setBoolean(9, ticket.isHasChildOption());
            preparedStatement.setString(10, ticket.getId());
            //执行更新操作
            preparedStatement.executeUpdate();
        }
    }

    // 将ResultSet对象映射到Ticket对象
   // 参数: resultSet - 包含机票信息的ResultSet对象
   // 返回值: 映射后的Ticket对象
  // 抛出: SQLException - 如果数据库操作失败
    private Ticket mapToTicket(ResultSet resultSet) throws SQLException {
        return new Ticket(
                resultSet.getString("id"),
                resultSet.getString("type"),
                resultSet.getString("ticketType"),
                resultSet.getString("departure_city"),
                resultSet.getString("arrival_city"),
                resultSet.getDate("departure_date").toLocalDate(),
                resultSet.getTime("start_time").toLocalTime(),
                resultSet.getTime("end_time").toLocalTime(),
                resultSet.getDouble("price"),
                resultSet.getBoolean("has_infant_option"),
                resultSet.getBoolean("has_child_option")
        );
    }
}
